import Dep from "./Dep";
export default class Watcher {
  constructor(target, expression, cb) {
    this.target = target;
    this.getter = parsePath(expression);
    this.value = this.get();
    this.cb = cb;
  }
  get() {
    let obj = this.target;
    Dep.target = this;
    let value = this.getter(obj);
    Dep.target = null;
    return value;
  }
  update() {
    this.getOrInvoke();
  }
  getOrInvoke() {
    console.log('==');
    let oldValue = this.value;
    let newValue = this.get();
    console.log(oldValue,newValue)
    if (oldValue !== newValue) {
      console.log(this.cb,'cb');
      this.cb(newValue, oldValue);
    }
  }
}
function parsePath(params) {
  let arrParams = params.split(".");
  return (target) => {
    let obj = target;
    arrParams.forEach((key) => {
      obj = obj[key];
    });
    return obj;
  };
}
